package com.rayboot.footpoint.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Checkable;
import android.widget.ImageView;

public class SwitchButton extends ImageView implements Checkable {
	private static final int[] CHECKED_STATE_SET;
	private boolean mChecked;
	private OnCheckedChangeListener mOnCheckedChangeListener;
	private View.OnTouchListener onTouchListener = new View.OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if (event.getAction() == MotionEvent.ACTION_UP) {
				SwitchButton.this.requestFocus();
			}
			return false;
		}
	};

	static {
		int[] arrayOfInt = new int[1];
		arrayOfInt[0] = android.R.attr.state_checked;
		CHECKED_STATE_SET = arrayOfInt;
	}

	public SwitchButton(Context context) {
		super(context);
		initView();
	}

	public SwitchButton(Context context, AttributeSet attributeSet) {
		super(context, attributeSet, 0);
		initView();
	}

	public SwitchButton(Context context, AttributeSet attributeSet, int paramInt) {
		super(context, attributeSet, paramInt);
		initView();
	}

	private void initView() {
		setClickable(true);
		setOnTouchListener(onTouchListener);
	}

	@Override
	public boolean isChecked() {
		return mChecked;
	}

	@Override
	public int[] onCreateDrawableState(int state) {
		int[] arrayOfInt = super.onCreateDrawableState(state + 1);
		if (isChecked())
			mergeDrawableStates(arrayOfInt, CHECKED_STATE_SET);
		return arrayOfInt;
	}

	@Override
	public boolean performClick() {
		toggle();
		return super.performClick();
	}

	@Override
	public void setChecked(boolean isChecked) {
		if (mChecked != isChecked) {
			mChecked = isChecked;
			refreshDrawableState();
			if (mOnCheckedChangeListener != null) {
				mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
			}
		}
	}

	public void setOnCheckedChangeListener(
			OnCheckedChangeListener paramOnCheckedChangeListener) {
		this.mOnCheckedChangeListener = paramOnCheckedChangeListener;
	}

	@Override
	public void toggle() {
		setChecked(!mChecked);
	}

	public static abstract interface OnCheckedChangeListener {
		public abstract void onCheckedChanged(SwitchButton switchButton,
				boolean state);
	}
}
